#include <string.h>
#include "PopupSSL.hpp"
#include "PopupBlowfishKeyMsg.hpp"
#include "PopupUtilities.hpp"

using namespace Popup;


BlowfishKeyMsg::BlowfishKeyMsg(const Message *p_message)
 : AbstractMessage(POPUP_MSG_TYPE_BLOWFISH_KEY, POPUP_ENCRYPTION_RSA)
{
  AbstractMessage::deserialize(p_message);
}

bool BlowfishKeyMsg::onSend()
{
  // Add encrypted key to payload
  return payloadAddData(BlowfishKeyMsg::BLOWFISH_KEY,
                        (const unsigned char*) sslContext->getBlowfishKey(),
                        sizeof(BlowfishKey));
}

bool BlowfishKeyMsg::onReceive()
{
  if (fields.size() != 1) {
    return false;
  } else {
    const MessageField *_field =
        AbstractMessage::payloadGetField(BLOWFISH_KEY);
    if (_field == 0) {
      return false;
    } else if (_field->size != sizeof(BlowfishKey)) {
      return false;
    } else {
      memcpy(receivedKey, _field->data, sizeof(BlowfishKey));
      return true;
    }
  }
}
